#include "salequerystandarditemmodel.h"
#define ITEM_INDEX_DINGDAN_VALUE 4 //订单-合计金额
#define ITEM_INDEX_DINGDAN_TICKET 5 //订单-合计票款
#define ITEM_INDEX_DINGDAN_MONEY 6 //订单-合计货款
#define ITEM_INDEX_DETAIL_VALUE 9 //订单-合计金额
#define ITEM_INDEX_DETAIL_TICKET 10 //订单-合计票款
#define ITEM_INDEX_DETAIL_MONEY 11 //订单-合计货款
SaleQueryStandardItemModel::SaleQueryStandardItemModel(QObject *parent) : QStandardItemModel(parent)
{

}

QVariant SaleQueryStandardItemModel::data(const QModelIndex &index, int role) const
{
    QVariant value = QStandardItemModel::data(index, role);
    if(widgetType == Profit){
        if(type ==0){
            if(index.column() == 3 || index.column()==4 || index.column() == header.size()-1){
                //设置内容居中
                if(role==Qt::TextAlignmentRole){
                    return  Qt::AlignRight;
                }
            }
        }else{
            if((index.column()>=7 && index.column()<=9) || index.column() == header.size()-1){
                //设置内容居中
                if(role==Qt::TextAlignmentRole){
                    return  Qt::AlignRight;
                }
            }
        }
    }

    return value;
}

void SaleQueryStandardItemModel::setWidgetType(WidgetType widgetType){
    this->widgetType = widgetType;
    if(widgetType == Sale){
        QStringList saleHeaderDingdan = {"单号",
                                         "时间",
                                         "类型",
                                         "合计数量",
                                         "合计金额",
                                         "应开发票",
                                         "应收货款",
                                         "客户名称",
                                         "联系人",
                                         "电话",
                                         "备注",
                                         "我方运费已付",
                                         "我方运费未付",
                                         "对方运费垫付",
                                         "免开票",
                                         "免收款",
                                         "开票",
                                         "收款"};
        QStringList saleHeaderDetail = {"单号",
                                        "时间",
                                        "类型",
                                        "商品ID",
                                        "型号",
                                        "名称",
                                        "单位",
                                        "数量",
                                        "单价",
                                        "金额",
                                        "应开发票",
                                        "应收货款",
                                        "客户名称",
                                        "联系人",
                                        "电话"};
        headerDingdan = saleHeaderDingdan;
        headerDetail = saleHeaderDetail;
    }else if(widgetType == Purchase){
        QStringList purchaseHeaderDingdan = {"单号",
                                             "时间",
                                             "类型",
                                             "合计数量",
                                             "合计金额",
                                             "应收发票",
                                             "应付货款",
                                             "供应商名称",
                                             "联系人",
                                             "电话",
                                             "备注",
                                             "我方运费已付",
                                             "我方运费未付",
                                             "对方运费垫付",
                                             "免收票",
                                             "免付款",
                                             "收票",
                                             "付款"};
        QStringList purchaseHeaderDetail = {"单号",
                                            "时间",
                                            "类型",
                                            "商品ID",
                                            "型号",
                                            "名称",
                                            "单位",
                                            "数量",
                                            "单价",
                                            "金额",
                                            "应收发票",
                                            "应付货款",
                                            "供应商名称",
                                            "联系人",
                                            "电话"};
        headerDingdan = purchaseHeaderDingdan;
        headerDetail = purchaseHeaderDetail;
    }else{
        QStringList profitHeaderDingdan = {"单号",
                                           "时间",
                                           "类型",
                                           "合计数量",
                                           "合计金额",
                                           "客户名称",
                                           "联系人",
                                           "电话",
                                           "毛利润",
                                           "毛利率"};
        QStringList profitHeaderDetail = {"单号",
                                          "时间",
                                          "类型",
                                          "商品ID",
                                          "型号",
                                          "名称",
                                          "单位",
                                          "数量",
                                          "单价",
                                          "金额",
                                          "客户名称",
                                          "联系人",
                                          "电话",
                                          "毛利润",
                                          "毛利率"};
        headerDingdan = profitHeaderDingdan;
        headerDetail = profitHeaderDetail;
    }

    header = headerDingdan;
    setHorizontalHeaderLabels(header);
}

void SaleQueryStandardItemModel::setType(int type){
    this->type = type;
    if(type == 0){
        header = headerDingdan;
    }else{
        header = headerDetail;
    }
}

void SaleQueryStandardItemModel::reset(){
    clear();
    dingdans.clear();
    details.clear();
    setHorizontalHeaderLabels(header);
}

void SaleQueryStandardItemModel::insertDingdan(Dingdan &dingdan){
    QList<QStandardItem*> rowData;

    if(widgetType == Profit &&
            (dingdan.type == Dingdan::TicketAdjust_Client ||
             dingdan.type == Dingdan::TicketAdjust_Giver)){
        return;
    }

    UserRelation *relation = dingdan.getUserRelation();
    double profitPercent = 0;
    double totalMoney = dingdan.totalMoney;
    if(totalMoney != 0.0){
        totalMoney = totalMoney>0?totalMoney:(-1)*totalMoney;
        profitPercent = dingdan.profit*100/totalMoney;
    }

    rowData.append(new QStandardItem(dingdan.dingdanId));
    rowData.append(new QStandardItem(dingdan.date));
    rowData.append(new QStandardItem(dingdan.getTypeStr()));
    rowData.append(new QStandardItem(QString("%1").arg(dingdan.totalCount)));
    rowData.append(new QStandardItem(QString("%1").arg(dingdan.totalMoney)));
    if(widgetType == Sale){
        rowData.append(new QStandardItem(QString("%1").arg(dingdan.ticketOut)));
        rowData.append(new QStandardItem(QString("%1").arg(dingdan.moneyIn)));
    }else if(widgetType == Purchase){
        rowData.append(new QStandardItem(QString("%1").arg(dingdan.ticketIn)));
        rowData.append(new QStandardItem(QString("%1").arg(dingdan.moneyOut)));
    }
    rowData.append(new QStandardItem(relation==nullptr?"":relation->nickName));
    rowData.append(new QStandardItem(relation==nullptr?"":relation->contact));
    rowData.append(new QStandardItem(relation==nullptr?"":relation->tel));
    if(widgetType == Profit){
        rowData.append(new QStandardItem(QString::number(dingdan.profit, 'f', 2)));
        rowData.append(new QStandardItem(QString::number(profitPercent, 'f', 2)+"%"));
    }else{
        rowData.append(new QStandardItem(dingdan.remark));
        rowData.append(new QStandardItem(QString::number(dingdan.sourceFreightPaid, 'f', 2)));
        rowData.append(new QStandardItem(QString::number(dingdan.sourceFreightUnpaid, 'f', 2)));
        rowData.append(new QStandardItem(QString::number(dingdan.targetFreightPaid, 'f', 2)));
        rowData.append(new QStandardItem(QString::number(dingdan.freeTicket, 'f', 2)));
        rowData.append(new QStandardItem(QString::number(dingdan.freeMoney, 'f', 2)));
        rowData.append(new QStandardItem(QString::number(dingdan.ticket, 'f', 2)));
        rowData.append(new QStandardItem(QString::number(dingdan.money, 'f', 2)));
    }

    appendRow(rowData);
    dingdans.append(&dingdan);
}

void SaleQueryStandardItemModel::insertDingdan(QList<Dingdan*> dingdans){
    for(Dingdan *dingdan:dingdans){
        insertDingdan(*dingdan);
    }

    refreshTotalProfit();
}

void SaleQueryStandardItemModel::insertDingdanDetail(DingdanAndDetail &detail){
    QList<QStandardItem*> rowData;

    if(widgetType == Profit &&
            (detail.dingdan.type == Dingdan::TicketAdjust_Client ||
             detail.dingdan.type == Dingdan::TicketAdjust_Giver)){
        return;
    }

    Product *product = detail.detail.getProduct();
    UserRelation *relation = detail.dingdan.getUserRelation();
    double profitPercent = 0;
    double totalMoney = detail.detail.count*detail.detail.price;

    rowData.append(new QStandardItem(detail.dingdan.dingdanId));
    rowData.append(new QStandardItem(detail.dingdan.date));
    rowData.append(new QStandardItem(detail.dingdan.getTypeStr()));
    rowData.append(new QStandardItem(product==nullptr?"":product->productId));
    rowData.append(new QStandardItem(product==nullptr?"":product->type));
    rowData.append(new QStandardItem(product==nullptr?"":product->name));
    rowData.append(new QStandardItem((detail.dingdan.type > 4)?"次":product==nullptr?"":product->unit));
    rowData.append(new QStandardItem(QString("%1").arg(detail.detail.count)));
    rowData.append(new QStandardItem(QString("%1").arg(detail.detail.price)));
    rowData.append(new QStandardItem(QString("%1").arg(totalMoney)));
    if(widgetType == Sale){
        rowData.append(new QStandardItem(QString("%1").arg(detail.detail.ticketOut)));
        rowData.append(new QStandardItem(QString("%1").arg(detail.detail.moneyIn)));
    }else if(widgetType == Purchase){
        rowData.append(new QStandardItem(QString("%1").arg(detail.detail.ticketIn)));
        rowData.append(new QStandardItem(QString("%1").arg(detail.detail.moneyOut)));
    }
    rowData.append(new QStandardItem(relation==nullptr?"":relation->nickName));
    rowData.append(new QStandardItem(relation==nullptr?"":relation->contact));
    rowData.append(new QStandardItem(relation==nullptr?"":relation->tel));
    if(widgetType == Profit){
        if(totalMoney != 0.0){
            totalMoney = totalMoney>0?totalMoney:(-1)*totalMoney;
            profitPercent = detail.detail.profit*100/totalMoney;
        }
        rowData.append(new QStandardItem(QString::number(detail.detail.profit, 'f', 2)));
        rowData.append(new QStandardItem(QString::number(profitPercent, 'f', 2)+"%"));
    }

    appendRow(rowData);
    details.append(&detail);
}

void SaleQueryStandardItemModel::insertDingdanDetail(QList<DingdanAndDetail*> details){
    for(DingdanAndDetail *detail:details){
        insertDingdanDetail(*detail);
    }

    if(widgetType == Profit){
        refreshTotalProfit();
    }else{
        refreshTotalValue();
    }
}

void SaleQueryStandardItemModel::refreshTotalProfit(){
    double totalProfit = 0;
    double totalMoney = 0;
    double averageProfit = 0;
    if(type == 0){
        //按订单
        for(Dingdan *dingdan:dingdans){
            totalProfit += dingdan->profit;
            totalMoney += dingdan->totalMoney;
        }
        if(totalMoney != 0.0){
            averageProfit = totalProfit*100/totalMoney;
        }
    }else{
        //按明细
        for(DingdanAndDetail *detail:details){
            totalProfit += detail->detail.profit;
            totalMoney += detail->detail.count*detail->detail.price;
        }
        if(totalMoney != 0.0){
            averageProfit = totalProfit*100/totalMoney;
        }
    }

    emit this->updateTotalProfit(totalProfit, averageProfit);
}

void SaleQueryStandardItemModel::refreshTotalValue(){
    double totalValue = 0.0;
    double totalTicket = 0.0;
    double totalMoney = 0.0;
    int itemIndexValue = 0;
    int itemIndexTicket = 0;
    int itemIndexMoney = 0;
    if(type == 0){
        itemIndexValue = ITEM_INDEX_DINGDAN_VALUE;
        itemIndexTicket = ITEM_INDEX_DINGDAN_TICKET;
        itemIndexMoney = ITEM_INDEX_DINGDAN_MONEY;
    }else{
        itemIndexValue = ITEM_INDEX_DETAIL_VALUE;
        itemIndexTicket = ITEM_INDEX_DETAIL_TICKET;
        itemIndexMoney = ITEM_INDEX_DETAIL_MONEY;
    }

    for(int i=0;i<rowCount();i++){
        QStandardItem *itemValue = item(i, itemIndexValue);
        QStandardItem *itemTicket = item(i, itemIndexTicket);
        QStandardItem *itemMoney = item(i, itemIndexMoney);
        if(itemValue == nullptr || itemTicket == nullptr || itemMoney == nullptr){
            qDebug()<<"item is null for row:"<<i;
            break;
        }
        totalValue += itemValue->text().toDouble();
        totalTicket += itemTicket->text().toDouble();
        totalMoney += itemMoney->text().toDouble();
    }

    emit updateTotalValue(totalValue, totalTicket, totalMoney);
}

QString SaleQueryStandardItemModel::getDingdanId(int index){
    if(type == 0){
        if(index < 0 || index >= dingdans.size()){
            return nullptr;
        }

        return dingdans[index]->dingdanId;
    }

    if(index < 0 || index >= details.size()){
        return nullptr;
    }

    return details[index]->detail.dingdanId;
}
